package com.lijiajia.cloud.common.security.resolver;


import com.lijiajia.cloud.common.security.user.DefaultCloudUser;
import com.lijiajia.cloud.common.security.user.ICloudUser;
import org.springframework.core.MethodParameter;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * CloudUserResolver
 *
 * @author lijiajia
 * @since 2019-04-15
 */
public class CloudUserResolver implements HandlerMethodArgumentResolver {
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		Class<?> parameterType = parameter.getParameterType();
		return parameterType.equals(ICloudUser.class) || parameterType.equals(DefaultCloudUser.class);
	}

	@Override
	public ICloudUser resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

		Object principal = webRequest.getUserPrincipal();

		if (principal instanceof OAuth2Authentication) {
			OAuth2Authentication authentication = (OAuth2Authentication) principal;
			if (authentication.getPrincipal() instanceof ICloudUser) {
				return (ICloudUser) authentication.getPrincipal();
			} else {
				return null;
			}
		}
		return null;
	}
}
